//
//  ViewController.m
//  01-WaiQingTong
//
//  Created by 李晓东 on 17/9/11.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//

#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "CommonConstant.pch"
#import "HomeCollectionViewCell.h"
#import <AVOSCloud.h>

#define kMargin 8
@interface ViewController ()<UICollectionViewDataSource, MKMapViewDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) UICollectionView *collectoinView;
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) CLLocationManager *locationManager;

@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, strong) AVObject *testObject;
@end
static NSString *cellId = @"pageACollectionCell";

@implementation ViewController
- (void)loadView{
    [super loadView];
    self.locationManager = [[CLLocationManager alloc]init];
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    [self.locationManager setDelegate:self];
    [self.locationManager startUpdatingLocation];
    [self.locationManager setDistanceFilter:10];
//    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    [self initView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.testObject = [AVObject objectWithClassName:@"Locations"];
    
}

// MARK: - 初始化控件方法
- (void)initView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    CGFloat cellWidth = 80;
    [layout setItemSize:CGSizeMake(cellWidth, cellWidth)];
    
    self.collectoinView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight / 2) collectionViewLayout:layout];
    
    CGFloat margin = (kScreenWidth - cellWidth * 3) / 4;
    [self.collectoinView setContentInset:UIEdgeInsetsMake(0, margin, 0, margin)];
    [self.collectoinView setBackgroundColor:[UIColor whiteColor]];
    
    [self.view addSubview:self.collectoinView];
    
    [self.collectoinView setDataSource:self];
    [self.collectoinView registerClass:[HomeCollectionViewCell class] forCellWithReuseIdentifier:cellId];
    
    // 设置地图
    self.mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, self.collectoinView.frame.size.height + kMargin, kScreenWidth, kScreenWidth)];
    [self.view addSubview:self.mapView];
    
    [self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
    //Setting this property to YES causes the map view to use the Core Location framework to find the current location and try to display it on the map \/
    [self.mapView setShowsUserLocation:YES];
    [self.mapView setDelegate: self];
    
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_queue_t queue = dispatch_get_main_queue();
//    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
//    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
//    uint64_t interval = (uint64_t)(1.0 * NSEC_PER_SEC);
    
    
//    dispatch_source_set_timer(self.timer, start, 5 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
//    dispatch_source_set_event_handler(self.timer, ^{
////        [self.locationManager startUpdatingLocation];
//    });
//    dispatch_resume(self.timer);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 9;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeCollectionViewCell *cell = (HomeCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    [cell setIcon:indexPath.item];
    
    return cell;
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    NSLog(@"ddj");
    for (CLLocation *location in locations) {
//        CLLocationCoordinate2D coordinates = [location coordinate];
        CLGeocoder *geocoder = [[CLGeocoder alloc]init];
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            for (CLPlacemark *placemark in placemarks) {
                NSLog(@"%@", [placemark subThoroughfare]);
                CLLocationCoordinate2D coordinates = placemark.location.coordinate;
                NSString *latStr = [NSString stringWithFormat:@"%f", coordinates.latitude];
                NSString *longStr = [NSString stringWithFormat:@"%f", coordinates.longitude];
                self.testObject = [AVObject objectWithClassName:@"Locations"];
                [self.testObject setObject:latStr forKey:@"lay"];
                [self.testObject setObject:longStr forKey:@"long"];
                // 用于保存轨迹
//                [self.testObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
//                    if (error != nil) {
//                        return ;
//                    }
//                    
//                }];
            }
        }];
    }
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    CLGeocoder *coder = [[CLGeocoder alloc]init];
    [coder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //4.1 防错处理
        if (placemarks.count == 0 || error) {
            NSLog(@"解析没有数据或者出错");
            return;
        }
        
        //4.2 遍历数组, 获取数据 --> 一般来讲就一个值
        for (CLPlacemark * placemark in placemarks) {
            NSLog(@"place---%@", placemark.locality);
        }
    }];
    NSLog(@"%f--%f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    
    
}
@end


